<template>
  <div class="hello">
    <el-card class="box-card">
      <div slot="header" class="clearfix" style="text-align: left;">
        <span>科泰头条后台登录</span>
      </div>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="100px" class="demo-ruleForm" status-icon>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" @blur="validateUsername" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="loginForm.password" @blur="validatePassword"></el-input>
        </el-form-item>
        <el-button type="primary" @click="submitForm">登录</el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: this.validatePasswordComplexity, trigger: 'blur' }
        ]
      }
    };
  },
  methods: {

    validatePasswordComplexity(rule, value, callback) {
      if (!value) {
        return callback(new Error('请输入密码'));
      }
      const regex = /^[a-zA-Z0-9_]{6,}$/;
      if (!regex.test(value)) {
        callback(new Error('密码必须6位数以上的数字字母下划线组成'));
      } else {
        callback();
      }
    },

    validateUsername() {
      this.$refs.loginFormRef.validateField('username');
    }, 

    validatePassword() {
      this.$refs.loginFormRef.validateField('password');
    },
    // 提交表单  
    submitForm() {
      this.$refs.loginFormRef.validate((valid) => {  
        if (valid) {   
          this.$message({  
            message: '校验成功!',  
            type: 'success'  
          });  
        } else {  
          console.log('error submit!!');  
        }  
      });   
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.box-card {
  width: 480px;
}
</style>
